package com.indiv.pmy.input;

import java.awt.Component;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.util.HashMap;

public class KeyboardMonitor implements KeyListener {
	private KeyboardState state;
	private HashMap<KeyValue,Boolean> monitor;
	private EventKeyMap ekm;
	
	boolean debug = false;
	
	public KeyboardMonitor(Component c) {
		state = new KeyboardState();
		monitor = new HashMap<KeyValue,Boolean>();
		
		ekm = new EventKeyMap();
		ekm.populateMap();
		c.addKeyListener(this);
	}
	
	public KeyboardMonitor(KeyValue[] toMonitor, Component c) {
		state = new KeyboardState();
		monitor = new HashMap<KeyValue,Boolean>();
		for(int i = 0; i < toMonitor.length; i++) {
			monitor.put(toMonitor[i],true);
			state.pushState(toMonitor[i], KeyState.NOTPRESSED);
		}
		ekm = new EventKeyMap();
		ekm.populateMap();
		c.addKeyListener(this);
	}
	
	public void registerKeyWithMonitor(KeyValue key) {
		state.pushState(key, KeyState.NOTPRESSED);
		monitor.put(key, true);
	}
	
	public void removeKeyFromMonitor(KeyValue key) {
		state.removeState(key);
		monitor.remove(key);
	}
	
	public void keyPressed(KeyEvent arg0) {
		if(debug) {
			System.out.println("keyPressedEvent: " + arg0.getKeyCode());
		}
		KeyValue k = ekm.get(arg0.getKeyCode());
		if(k != null && monitor.get(k)!=null) {
			state.pushState(k, KeyState.PRESSED);
		}
	}

	public void keyReleased(KeyEvent arg0) {
		KeyValue k = ekm.get(arg0.getKeyCode());
		if(k != null && monitor.get(k)!=null) {
			state.pushState(k, KeyState.NOTPRESSED);
		}
	}

	public KeyboardState getKeyboardState() {
		return state.clone();
	}
	
	public void keyTyped(KeyEvent arg0) {
		//we don't handle this particular event
	}
	
}
